#include"spi.h"

void spi_init(void)
{
    //开启时钟 
    RCC->APB2ENR|=RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR|=RCC_APB2ENR_IOPCEN;
    RCC->APB2ENR|=RCC_APB2ENR_SPI1EN;

    //配置GPIO PA5 PA7  复用推挽输出 MODE 11 CNF 10      PA6 浮空输入 MODE 00 CNF 01   PC13 通用推挽输出
    GPIOA->CRL|=(GPIO_CRL_MODE5|GPIO_CRL_MODE7);
    GPIOA->CRL|=(GPIO_CRL_CNF5_1|GPIO_CRL_CNF7_1);
    GPIOA->CRL&=~(GPIO_CRL_CNF5_0|GPIO_CRL_CNF7_0);

    GPIOC->CRH|=GPIO_CRH_MODE13;
    GPIOC->CRH&=~GPIO_CRH_CNF13;

    GPIOA->CRL&=~GPIO_CRL_MODE6;
    GPIOA->CRL&=~GPIO_CRL_CNF6_1;
    GPIOA->CRL|=GPIO_CRL_CNF6_0;

    //配置SPI
    //配置为主模式
    SPI1->CR1|=SPI_CR1_MSTR;

    //配置软件片选
    SPI1->CR1|=SPI_CR1_SSM;
    SPI1->CR1|=SPI_CR1_SSI;

    //分频
    SPI1->CR1&=~SPI_CR1_BR;
    SPI1->CR1|=SPI_CR1_BR_0;
    //模式0
    SPI1->CR1&=~SPI_CR1_CPHA;
    SPI1->CR1&=~SPI_CR1_CPOL;

    //高位先行
    SPI1->CR1&=~SPI_CR1_LSBFIRST;

    //8位数据帧格式
    SPI1->CR1&=~SPI_CR1_DFF;

    //使能
    SPI1->CR1|=SPI_CR1_SPE;

}

void spi_start(void)
{
    SPI_CS_LOW;

}

void spi_stop(void)
{
    SPI_CS_HIGH;

}

uint8_t spi_swapdata(uint8_t data)
{
    while ((SPI1->SR & SPI_SR_TXE)==0)
    {
    }
    SPI1->DR=data;

    while ((SPI1->SR & SPI_SR_RXNE)==0)
    {
    }
    
    return (uint8_t)(SPI1->DR);
    
}
